<!--
 * @Description: 
 * @Author: qingyang
 * @Date: 2022-01-11 19:05:29
 * @LastEditors: chenju
 * @LastEditTime: 2023-02-02 10:13:53
-->
<template>
  <div class="organization-form">
    <!-- <GPageHeader title="组织详情" :isBack="false" /> -->
    <template v-if="data?.organizationCode || data?.id">
      <div class="organization-content">
        <div class="desc-area">
          <div class="line"></div>
          <!-- 头部描述 -->
          <div class="organization-desc">
            <div class="title">
              <!-- 左侧标题 -->
              <div class="left">
                <span class="left-title g-mr6">{{ empty(form.organizationName) }}</span>
                <span class="left-code g-mr6" v-if="form.organizationCode">{{
                  form.organizationCode
                }}</span>
                <el-tag v-if="enterpriseName" class="tag org-tag" type="info">{{
                  enterpriseName
                }}</el-tag>
                <el-tag class="org-tag" :class="`tag-${form.tag}`" v-if="form.tag">{{
                  OrgTagMap[form.tag]
                }}</el-tag>
              </div>
              <!-- 右侧按钮 -->
              <el-button
                class="rightButton"
                text
                type="primary"
                @click="handleEdit"
                v-btnPermission="'ORGANIZATION_EDIT'"
              >
                <template #icon>
                  <CIcon type="c-xian-bianji" class="editIcon"></CIcon>
                </template>
                <span class="editText">编辑</span>
              </el-button>
            </div>
            <div class="desc">
              <!-- 描述 -->
              <span class="desc-item">企业名称：{{ empty(form.companyName) }}</span>
              <template v-if="form.organizationCategory == OrgTypeEnum.ENTITY">
                <el-divider direction="vertical" />
                <span class="desc-item">所属行业：{{ empty(IndustryMap[form.industry]) }}</span>
                <el-divider direction="vertical" />
                <span class="desc-item">统一社会信用代码：{{ empty(form.uscc) }}</span>
              </template>
            </div>
          </div>
          <!-- 表格信息展示 -->
          <div class="table" v-if="form.organizationCategory == OrgTypeEnum.ENTITY">
            <table class="organization-table" align="center" cellpadding="0" cellspacing="0">
              <tr class="table-bg">
                <td>法定代表人</td>
                <td>联系人</td>
                <td>联系电话</td>
                <td>联系邮箱</td>
              </tr>
              <tr>
                <td>{{ empty(form.legalPerson) }}</td>
                <td>{{ empty(form.contact) }}</td>
                <td>{{ empty(form.contactPhone) }}</td>
                <td>{{ empty(form.contactEmail) }}</td>
              </tr>
              <tr class="table-bg">
                <td>成立日期</td>
                <td>注册资本（万元）</td>
                <td colspan="2">注册地址</td>
              </tr>
              <tr>
                <td>{{ empty(establishmentDate) }}</td>
                <td>{{ thousandFormat(form.registeredCapital) }}</td>
                <td colspan="2">{{ empty(form.registeredAddress) }}</td>
              </tr>
              <tr class="table-bg">
                <td colspan="2">经营范围</td>
                <td colspan="2">公司经营地址</td>
              </tr>
              <tr>
                <td colspan="2">{{ empty(form.businessScope) }}</td>
                <td colspan="2">{{
                  empty(
                    (form.provinceName || '') + (form.cityName || '') + (form.companyAddress || '')
                  )
                }}</td>
              </tr>
            </table>
          </div>
        </div>
        <div class="organization-list" v-if="!isNew">
          <div class="list-label">
            <span>账号列表({{ userList.length || '0' }})</span>
            <el-button @click="addUser" v-btnPermission="'USER_ORGANIZATION_EDIT'">
              <template #icon>
                <CIcon type="c-xian-xinjian"></CIcon>
              </template>
              添加账号</el-button
            >
          </div>
          <CTable :data-source="userList" useDataSource :pagination="false">
            <vxe-column title="用户账号">
              <template #default="scope">
                <span>{{ empty(scope.row.username) }}</span>
              </template>
            </vxe-column>
            <vxe-column title="用户名称">
              <template #default="scope">
                <span>{{ empty(scope.row.realName) }}</span>
              </template>
            </vxe-column>
            <vxe-column title="用户角色">
              <template #default="scope">
                <span>{{ empty(scope.row.roleName) }}</span>
              </template>
            </vxe-column>
            <vxe-column title="操作" width="100">
              <template #default="scope">
                <CTableButtonGroup :buttons-config="getTableButtonsConfig(scope.row)" />
              </template>
            </vxe-column>
          </CTable>
        </div>
      </div>
    </template>
  </div>
  <CSelectUserDialog v-model:visible="dialogVisible" @confirm="handleConfirm"></CSelectUserDialog>
  <editOrganizationDialog
    :formData="data"
    v-if="editDialogVisible"
    v-model:visible="editDialogVisible"
  />
</template>

<script lang="ts">
export default {
  name: 'OrganizationForm'
};
</script>
<script lang="ts" setup>
import { defineProps, ref, watch, computed, withDefaults } from 'vue';
import { empty, thousandFormat } from '@/utils/index';
import { IndustryMap } from '@/constants/enum';
import CSelectUserDialog from '@/businessComponents/CSelectUserDialog/index.vue';
import { useMessage } from '@/hooks/useMessage';
import { CTable } from '@/components/CTable/index';

import {
  AddUserOrganizationParams,
  userItem,
  GetOrganizationTreeResult
} from '@/apis/system/model/organizationModel';
import {
  addUserOrganization,
  deleteUserOrganization,
  getOrganizationDetail
} from '@/apis/system/organization';
import { store } from '@/store';
import { CompanyTypeOptions, OrgTagMap, OrgTypeEnum } from '@/constants/enum';
import editOrganizationDialog from './editOrganizationDialog.vue';
import { CTableButtonGroup } from '@/components/CTable';
import type { TableButtonItem } from '@/components/CTable';

interface IProps {
  data: GetOrganizationTreeResult;
}
const props = withDefaults(defineProps<IProps>(), {
  data: () => {
    return {} as GetOrganizationTreeResult;
  }
});
const { createMessage } = useMessage();
watch(
  () => props.data,
  () => {
    console.log('props.data', props.data);
    if (props.data.organizationCode) {
      getDetail(props.data.id);
      isNew.value = false;
    } else {
      isNew.value = true;
      form.value = {
        organizationName: '',
        companyName: '',
        province: '',
        city: '',
        companyAddress: '',
        contact: '',
        contactPhone: '',
        contactEmail: '',
        uscc: '',
        companyType: '',
        legalPerson: '',
        establishmentDate: '',
        registeredCapital: '',
        registeredAddress: '',
        industry: '',
        businessScope: ''
      };
    }
  }
);

const getDetail = (id: number) => {
  getOrganizationDetail(id).then(res => {
    form.value = res;
    userList.value = res.userList ?? [];
  });
};

const form = ref<any>({
  organizationName: '',
  companyName: '',
  province: '',
  city: '',
  companyAddress: '',
  contact: '',
  contactPhone: '',
  contactEmail: '',
  uscc: '',
  companyType: '',
  legalPerson: '',
  establishmentDate: '',
  registeredCapital: '',
  registeredAddress: '',
  industry: '',
  businessScope: ''
});

const userList = ref<userItem[]>([]);
const dialogVisible = ref(false);
const { createConfirm } = useMessage();
const isNew = ref(true);
// 新增账户按钮点击操作
function addUser() {
  dialogVisible.value = true;
}

const dialogLoading = ref<boolean>(false);
// 新增账户弹窗 确认操作
function handleConfirm(id: string) {
  const params: AddUserOrganizationParams = {
    // 用户Id
    userId: id,
    // 组织Id
    organizationId: props.data.id
  };
  dialogLoading.value = true;
  addUserOrganization(params)
    .then(() => {
      createMessage.success('添加用户成功！');
      dialogVisible.value = false;
      dialogLoading.value = false;
      getDetail(props.data.id);
    })
    .catch(() => {
      dialogLoading.value = false;
    });
}

// 点击删除用户操作
const deleteUser = (row: any) => {
  createConfirm('确定移除账号吗？', '移除账号和组织的关联关系。', {
    iconType: 'warning'
  }).then(() => {
    console.log('row', row);
    const params: AddUserOrganizationParams = {
      // 用户Id
      userId: row.userId,
      // 组织Id
      organizationId: props.data.id
    };
    deleteUserOrganization(params).then(() => {
      createMessage.success('删除成功！');
      getDetail(props.data.id);
    });
  });
};

// 当前登录用户
const userId = computed(() => {
  return store.state.user.userInfo.userId;
});

function getTableButtonsConfig(row: any): TableButtonItem[] {
  if (row.userId === userId.value) {
    return [];
  }
  return [
    {
      text: '移除',
      btnPermission: 'USER_ORGANIZATION_EDIT',
      onClick: () => deleteUser(row)
    }
  ];
}
const editDialogVisible = ref(false);
const handleEdit = () => {
  editDialogVisible.value = true;
};

// 企业名称
const enterpriseName = computed(() => {
  const a = CompanyTypeOptions.find((i: any) => {
    return form.value.companyType === i.value;
  });
  return a?.label;
});
// 成立日期
const establishmentDate = computed(() => {
  if (form.value.establishmentDate) {
    const date = new Date(form.value.establishmentDate);
    let year = date.getFullYear(); // 2022
    let month = date.getMonth() + 1; // 5,这里月份范围是0-11，因此需要减一
    let day = date.getDate(); // 15
    return `${year}年${month}月${day}日`;
  } else {
    return '';
  }
});
</script>
<style lang="scss" scoped>
.organization-form {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .organization-footer {
    height: 56px;
    padding: 0 24px;
    border-top: 1px solid #e4e7ed;
    line-height: 56px;
  }
}
.organization-content {
  flex: 1;
  padding: 16px;
  overflow: auto;
  background-color: #f3f7fb;
  .desc-area {
    width: 100%;
    background-color: #fff;
    padding-bottom: 20px;
    border-radius: 3px;
    overflow: hidden;
    .line {
      width: 100%;
      height: 2px;
      background: #028968;
      border-radius: 3px;
    }
    .organization-desc {
      padding: 16px 20px 14px;
      .title {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .left {
          display: flex;
          align-items: center;
          .left-title {
            margin-right: 6px;
            font-size: 16px;
            font-family: PingFangSC-Semibold, PingFang SC;
            font-weight: 600;
            color: #0a1f33;
            line-height: 24px;
          }
          .left-code {
            font-size: 14px;
            font-family: PingFang SC;
            color: #0a1f33;
            line-height: 24px;
          }
          .tag {
            background: #f8fbfc;
            border: 1px solid #ebeff2;
            font-size: 12px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #5a739a;
            line-height: 20px;
          }
        }
        .rightButton {
          .editIcon {
            font-size: 16px;
            color: #435970;
          }
          .editText {
            font-size: 14px;
            font-weight: 400;
            color: #435970;
          }
        }
      }

      .desc {
        .desc-item {
          font-size: 14px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #435970;
          line-height: 22px;
        }
      }
    }
  }

  .table {
    padding: 0 20px;
  }
  .organization-table {
    width: 100%;
    border-collapse: collapse;
    border-radius: 3px; /*圆角*/
    overflow: hidden; /*有背景颜色就要用这个*/
    td {
      width: 25%;
      padding-left: 12px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #435970;
      line-height: 22px;
      border: 1px solid #ebeff2;
    }
    tr {
      height: 32px;
    }
  }
  .table-bg {
    transition: all 0.3s;
    background-color: #f3f7fb;
    td {
      font-size: 12px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #7a8a99;
      line-height: 20px;
    }
  }
  .el-input {
    width: 480px;
    :deep(.el-input__wrapper) {
      box-shadow: 0 0 0 1px #e4e7ed inset;
    }
  }
  :deep(.el-form--default.el-form--label-top .el-form-item .el-form-item__label) {
    line-height: 32px;
    margin-bottom: 0;
  }
  .address-select {
    .el-select {
      width: 160px;
      margin-right: 8px;
    }
  }
}
.organization-list {
  background-color: #fff;
  padding: 0 16px 32px;
  border-radius: 4px;
  width: 100%;
  margin-top: 16px;
  overflow: hidden;
  border-bottom: 0px;
  .list-label {
    height: 56px;
    font-size: 14px;
    font-weight: bold;
    color: #212529;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  :deep(.el-table th.el-table__cell) {
    font-size: 12px;
    font-weight: 500;
    color: #212529;
  }
  :deep(.el-table .cell) {
    padding-left: 20px;
  }

  .del-button {
    color: #308bf2;
    padding-left: unset;
  }
}
.user-form {
  .user-info {
    background: #f6f9fa;
    border-radius: 4px;
    padding: 12px 16px;

    .user-account {
      font-size: 14px;
      font-weight: bold;
      color: #212529;
      margin-bottom: 18px;
    }
    .user-name {
      font-size: 14px;
      font-family: SourceHanSansCN-Regular, SourceHanSansCN;
      font-weight: 400;
      color: #51596c;
      line-height: 20px;
      margin-top: 4px;
    }
  }
}
</style>
